/* 
和update.js 不同的是多接受了服务端更新内容字段 content
可以自定义更新界面 /hybrid/html/upgrade.html
 */

var UpdateVersion = function (){
	//此处为自动获取plus版本号
	this.version = '1.0.0',
	this.updateApi = 'https://app.lctlcb.com/api/site/config'
}
UpdateVersion.prototype = {
	//版本号对比, curV 大于 reqV返回true
	compare: function(curV, reqV){
		if(curV && reqV){
	      //将两个版本号拆成数字
	      var arr1 = curV.split('.'),
	          arr2 = reqV.split('.');
	      var minLength = Math.min(arr1.length, arr2.length),
	          position = 0,
	          diff = 0;
	      //依次比较版本号每一位大小，当对比得出结果后跳出循环
	      while(position < minLength && ((diff=parseInt(arr1[position]) - parseInt(arr2[position])) == 0)){
	          position++;
	      }
	      diff = (diff!=0) ? diff : (arr1.length-arr2.length);
	      //若curV大于reqV，则返回true
	      return diff > 0;
		}else{
	      //输入为空
	      console.log('版本号不能为空');
	      return false;
	   }
	},
	//热更新检测
	getNewData: function(type){
		var _this = this
		if(plus && plus.runtime.appid){
			uni.request({
				url: _this.updateApi,
				method: 'GET',
				success: (res)=>{
					var res = res.data.data
					if(_this.compare(res.version, _this.version)){
						//弹出更新提示
						 //version 最新版的版本号
						 //download_url 最新版的热更新地址
						 //forced_update 是否强制更新
						 //update_type 1=整包更新，其他wgt热更新
						 //update_type==1 是 apk_url, ipa_url
						if(res.type && res.update_type == 1){
							var downUrl = {
								android: res.apk_url,				 
								ios: res.ipa_url				 
							}
							_this.alertUpdateTips(res.download_url, res.force_update, downUrl)
						}else{
							_this.alertUpdateTips(res.download_url, res.force_update)
						}
						
					}else{
						if(type){
							plus.nativeUI.toast('当前已经是最新版本')
						}
					} 
				}
			})
		}else{
			console.log('当前环境不检测版本')
			if(type){
				uni.showToast({
					title: '当前已经是最新版本',
					icon: 'none'
				})
			}
		}
	},
	//弹出更新提示
	alertUpdateTips: function(url, forced_update, downUrl){
		let webview_style = {
			popGesture: "none",
			scrollIndicator:'none',
			hardwareAccelerated:true,
			background: 'transparent',
			bounce:'none',
			top: 0,
			left: 0,
			height: '100%',
			width: '100%',
		}
		var webview = plus.webview.create('/hybrid/html/upgrade.html', 'upgrade', webview_style, {
			content: `1.修复了bug </br>2.优化用户体验 </br>3.新增XXX功能`,
			forcedUpdate: forced_update,
			hotPackageUrl: url,
			downUrl: downUrl
		});
		webview.addEventListener('titleUpdate', function () {
			webview.show();
		});
	},
	//下载安装包
	downloadPack: function(url){
		var _this = this
		var w = plus.nativeUI.showWaiting('下载更新中');
		var totalSize = 0
		var dtask = plus.downloader.createDownload(url, { method: 'GET', filename: '_downloads/'},function(d,status){
			plus.nativeUI.closeWaiting();
			if(status == 200){
				_this.installPack(d.filename);
			}else{//下载失败
				plus.nativeUI.closeWaiting();
				plus.nativeUI.toast('下载失败');
			}
		});
		dtask.addEventListener("statechanged", function(download, status){
			if(download.state == 2){
				totalSize = d.totalSize
				totalSize = Math.round(parseInt(totalSize) / (1024 * 1024 / 100)) / 100;
			}
	    	if(download.state == 3 && totalSize){
	    		//已下载 download.downloadedSize
	    		//任务大小 download.totalSize
	    		var ds = Math.round(parseInt(download.downloadedSize) / (1024 * 1024 / 100)) / 100;
	    		w.setTitle(`更新进度:${ds}M/${totalSize}M`);
	    	}
	    }, false);
		dtask.start();
	},
	//安装
	installPack: function(path){
		var _this = this
		plus.nativeUI.showWaiting("安装更新文件中...");
		plus.runtime.install(path,{},function(){
			plus.nativeUI.closeWaiting();
			_this.tipReload()
		},function(e){
			plus.nativeUI.closeWaiting();
			plus.nativeUI.toast('安装失败')
		});
	},
	//提示重启
	tipReload: function(){
		if(plus.os.name == 'Android'){
			plus.nativeUI.confirm('最新版安装完成，是否立即重启APP?', function(e){
				if(e.index == 0){
					plus.runtime.restart();
		        }
			})
		}else{
			plus.nativeUI.alert('更新成功,重启APP后即可使用最新版！');	
		}
	},
	//整包更新
	updatePackage (url){
		if(plus.os.name == 'Android'){
			if(/\.apk$/.test(url.android)){
				this.downloadPack(url.android)
			}else{
				plus.runtime.openURL(url.android)
			}
		}else{
			if(/\.ipa$/.test(url.ios)){
				this.downloadPack(url.ios)
			}else{
				plus.runtime.openURL(url.ios)
			}
		}
	}
}

export default UpdateVersion